<?php

use Illuminate\Support\Facades\Route;
use App\Services\WordPressAuthService;

// 基础路由，不使用任何中间件
Route::get('/', function () {
    return response('Laravel Application is running in WordPress Plugin');
});

// 文档路由 - 使用与API相同的前缀，并添加WordPress管理员权限检查
$prefix = defined('WP_LARA_PRESS_API_PREFIX') ? WP_LARA_PRESS_API_PREFIX : 'api';

// 文档路由组，不使用web中间件，避免session问题
Route::prefix($prefix)->group(function () {

    // Scribe 文档路由 - 需要WordPress管理员权限
    Route::get('/docs', function () {
        // 检查WordPress权限
        $authCheck = WordPressAuthService::checkAdminAccess();
        if ($authCheck) return $authCheck;

        // 动态设置Scribe配置
        config(['scribe.base_url' => \App\Services\WordPressAssetService::getApiBaseUrl()]);

        // 使用Scribe生成的视图（已修复资源路径）
        return response()->view('scribe.index')->header('Content-Type', 'text/html');
    })->name('scribe');

    Route::get('/docs.postman', function () {
        // 检查WordPress权限
        $authCheck = WordPressAuthService::checkAdminAccess();
        if ($authCheck) return $authCheck;

        $collection = storage_path('app/private/scribe/collection.json');
        if (file_exists($collection)) {
            return response()->file($collection, [
                'Content-Type' => 'application/json',
                'Content-Disposition' => 'attachment; filename="postman-collection.json"'
            ]);
        }
        return response('Postman collection not found', 404);
    })->name('scribe.postman');

    Route::get('/docs.openapi', function () {
        // 检查WordPress权限
        $authCheck = WordPressAuthService::checkAdminAccess();
        if ($authCheck) return $authCheck;

        $openapi = storage_path('app/private/scribe/openapi.yaml');
        if (file_exists($openapi)) {
            return response()->file($openapi, [
                'Content-Type' => 'application/x-yaml',
                'Content-Disposition' => 'attachment; filename="openapi.yaml"'
            ]);
        }
        return response('OpenAPI spec not found', 404);
    })->name('scribe.openapi');
});
